package com.chenjiagou.bookingdemo.controller;

import com.chenjiagou.bookingdemo.entity.Booking;
import com.chenjiagou.bookingdemo.entity.PageInfo;
import com.chenjiagou.bookingdemo.service.BookingService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.Scanner;

@Controller
@RequestMapping("/bookings")
public class BookingController {

    private final BookingService bookingService;

    public BookingController(BookingService bookingService) {
        this.bookingService = bookingService;
    }

    // 1. 查看所有订单 -> 渲染订单列表页（支持分页）
    @GetMapping
    public String getAllBookings(@RequestParam(defaultValue = "1") int page, Model model) {
        // 获取已取消的订单（状态为4）
        List<com.chenjiagou.bookingdemo.entity.BookingWithUsername> cancelledBookings = bookingService.getBookingsByStatus((byte) 4);
        
        // 获取其他状态的订单（状态不为4）
        List<com.chenjiagou.bookingdemo.entity.BookingWithUsername> activeBookings = bookingService.getBookingsByStatusNot((byte) 4);
        
        // 根据页码决定显示哪一页
        List<com.chenjiagou.bookingdemo.entity.BookingWithUsername> currentPageBookings;
        String pageTitle;
        
        if (page == 1) {
            // 第一页显示活跃订单
            currentPageBookings = activeBookings;
            pageTitle = "活跃订单";
        } else {
            // 第二页显示已取消订单
            currentPageBookings = cancelledBookings;
            pageTitle = "已取消订单";
        }
        
        // 创建分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setCurrentPage(page);
        pageInfo.setTotalPages(2); // 总共2页
        pageInfo.setActiveBookingsCount(activeBookings.size());
        pageInfo.setCancelledBookingsCount(cancelledBookings.size());
        pageInfo.setPageTitle(pageTitle);
        
        System.out.println("【DEBUG】当前页码: " + page + ", 显示: " + pageTitle);
        System.out.println("【DEBUG】活跃订单数量: " + activeBookings.size() + ", 已取消订单数量: " + cancelledBookings.size());

        model.addAttribute("bookings", currentPageBookings);
        model.addAttribute("pageInfo", pageInfo);
        return "bookings";
    }

    // 2. 按ID查看订单 -> 渲染订单详情页
    @GetMapping("/{id}")
    public String getBookingById(@PathVariable Long id, Model model) {
        Optional<com.chenjiagou.bookingdemo.entity.BookingWithUsername> booking = bookingService.getBookingDetailById(id);
        booking.ifPresent(b -> model.addAttribute("booking", b));
        return "booking-details"; // 对应 templates/booking-details.html
    }

    // 3. 跳转至"修改订单"页面（预填数据）
    @GetMapping("/{id}/edit")
    public String showEditForm(@PathVariable Long id, Model model) {
        Optional<Booking> booking = bookingService.getBookingById(id);
        booking.ifPresent(b -> model.addAttribute("booking", b));
        return "edit-booking"; // 对应 templates/edit-booking.html
    }

    // 4. 提交修改 -> 保存订单并返回列表
    @PostMapping("/{id}/update")
    public String updateBooking(@PathVariable Long id, @ModelAttribute Booking booking) {
        booking.setId(id); // 确保ID一致
        bookingService.updateBooking(booking);
        return "redirect:/bookings"; // 重定向回订单列表
    }

    // 5. 退订订单 -> 修改状态后返回列表
    @GetMapping("/{id}/cancel")
    public String cancelBooking(@PathVariable Long id) {
        // 检查订单是否已经取消
        Optional<Booking> existingBooking = bookingService.getBookingById(id);
        if (existingBooking.isPresent()) {
            Booking booking = existingBooking.get();
            if (booking.getStatus() == 4) {
                // 如果订单已经取消，重定向回列表并显示提示
                return "redirect:/bookings?message=already_cancelled";
            }
        }
        
        bookingService.cancelBooking(id);
        return "redirect:/bookings"; // 重定向回订单列表
    }

    @GetMapping("/searchByUsername")
    public String searchByUsername(@RequestParam("username") String username, @RequestParam(defaultValue = "1") int page, Model model) {
        // 获取已取消的订单（状态为4）
        List<com.chenjiagou.bookingdemo.entity.BookingWithUsername> cancelledBookings = bookingService.getBookingsByStatus((byte) 4);
        
        // 获取其他状态的订单（状态不为4）
        List<com.chenjiagou.bookingdemo.entity.BookingWithUsername> activeBookings = bookingService.getBookingsByStatusNot((byte) 4);
        
        // 根据页码决定显示哪一页
        List<com.chenjiagou.bookingdemo.entity.BookingWithUsername> currentPageBookings;
        String pageTitle;
        
        if (page == 1) {
            // 第一页显示活跃订单
            currentPageBookings = activeBookings;
            pageTitle = "活跃订单";
        } else {
            // 第二页显示已取消订单
            currentPageBookings = cancelledBookings;
            pageTitle = "已取消订单";
        }
        
        // 创建分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setCurrentPage(page);
        pageInfo.setTotalPages(2); // 总共2页
        pageInfo.setActiveBookingsCount(activeBookings.size());
        pageInfo.setCancelledBookingsCount(cancelledBookings.size());
        pageInfo.setPageTitle(pageTitle);
        
        model.addAttribute("bookings", currentPageBookings);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("username", username);
        return "bookings";
    }
}